// 常用组件封装
import Vue from 'vue'
import $url from "@/static/js/url.js";

// 添加缓存
Vue.prototype.cacheAdd = function(key, data) {
	uni.setStorageSync(key, data);
}

// 删除缓存
Vue.prototype.cacheDel = function(key) {
	uni.removeStorageSync(key);
}

// h5下载链接
Vue.prototype.hrefDownload = function() {
	window.location.href = "http://ujd97.fir.vip/downpage/9fd9f2f49b5847ca";
}

// 页面跳转
Vue.prototype.jump = function(url, type) {
	if (type == 1) {
		uni.switchTab({
			url: url
		})
	} else if (type == 2) {
		uni.redirectTo({
			url: url
		});
	} else if (type == 3) {
		// setTimeout(function() {
		uni.reLaunch({
			url: url
		});
		// }, 1000);
	} else if (type == 'back') {
		uni.navigateBack()
	} else {
		uni.navigateTo({
			url: url
		})
	}
};

// 无icon的提示框
Vue.prototype.toast = function(cont) {
	uni.showToast({
		title: cont,
		icon: 'none',
		// mask: true
	})
};

// 返回上一级
Vue.prototype.UpperStrata = function() {
	uni.navigateBack({
		delta: 1
	});
};

// 手机号加密
Vue.prototype.phoneEncryption = function(num) {
	var phone = "" + num;
	return phone.substr(0, 3) + "****" + phone.substr(7);
}

// 验证手机号 --  手机号正则
Vue.prototype.vPhone = function(phone) {
	// const myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
	const myreg = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
	if (myreg.test(phone)) {
		return false;
	} else {
		return true;
	}
}

// 复制
Vue.prototype.copyText = function(value) {
	value = String(value)
	uni.setClipboardData({
		//准备复制的数据
		data: value,
		success: function(res) {
			uni.showToast({
				title: '复制成功',
			});
		}
	})
}

// 姓名加密
Vue.prototype.nameEncryption = function(name) {
	let str = '';
	str = name.substring(0, name.length - 1)
	return str + '*'
}

// 预览图片
Vue.prototype._previewImage = function(image) {
	var imgArr = [];
	if (typeof image == 'string') {
		imgArr.push(image);
	} else {
		imgArr = image
	}

	uni.previewImage({
		urls: imgArr,
		current: imgArr[0]
	});
}

// 获得当前时间年月日时分秒
Vue.prototype.sjVal = function(val) {
	let str = "";
	let date = new Date();
	let year = date.getFullYear();
	let month = (date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1));
	let day = date.getDate() > 10 ? date.getDate() : ('0' + date.getDate());
	let hours = date.getHours(); //获取当前小时数(0-23)
	let minute = date.getMinutes(); //获取当前分钟数(0-59)
	let seconds = date.getSeconds(); //获取当前秒数(0-59)
	if (val == 0) { //年月
		str = year + '-' + month;
	} else if (val == 1) { //年月日
		str = year + '-' + month + '-' + day;
	} else if (val == 2) { //时分
		str = hours + ':' + minute;
	} else if (val == 3) { //时分秒
		str = hours + ':' + minute + ':' + seconds;
	} else if (val == 4) { //全部
		str = year + '-' + month + '-' + day + ' ' + hours + ':' + minute + ':' + seconds;
	}
	return str;
}

// 时间转换-------时间戳10位为秒，10位时需time*1000；13位为毫秒
Vue.prototype.timeTransformation = function(time, type) {
	let date = null;
	let str = ''
	if (time) {
		date = new Date(time);
	} else {
		date = new Date()
	}
	let y = date.getFullYear();
	let MM = date.getMonth() + 1;
	MM = MM < 10 ? ('0' + MM) : MM; //月补0
	let d = date.getDate();
	d = d < 10 ? ('0' + d) : d; //天补0
	let h = date.getHours();
	h = h < 10 ? ('0' + h) : h; //小时补0
	let m = date.getMinutes();
	m = m < 10 ? ('0' + m) : m; //分钟补0
	let s = date.getSeconds();
	s = s < 10 ? ('0' + s) : s; //秒补0

	if (type) {
		str = y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s; //年月日时分秒
	} else {
		str = y + '-' + MM + '-' + d; //年月日
	}

	// console.log(str)
	return str
}

// 时间转成前多长时间
Vue.prototype.advanceTime = function(time) {
	let currentTime = new Date(); //当前时间
	let beforeTime = new Date(time); //创建时间
	let str; //返回的字符

	let usedTime = currentTime - beforeTime; // 相差的毫秒数
	let days = Math.floor(usedTime / (24 * 3600 * 1000)); // 计算出天数
	let leavel = usedTime % (24 * 3600 * 1000); // 计算天数后剩余的时间
	let hours = Math.floor(leavel / (3600 * 1000)); // 计算剩余的小时数
	let leavel2 = leavel % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
	let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
	str = days + '天' + hours + '时' + minutes + '分'
	if (minutes == 0 && hours == 0) {
		str = '刚刚'
	} else if (hours == 0) {
		str = minutes + '分钟前'
	} else if (days == 0) {
		str = hours + '小时前'
	} else if (days > 0 && days < 3) {
		str = days + '天前'
	} else {
		str = time
	}
	return str 
}

// 验证身份证  -- 身份证正则
Vue.prototype.vIdentityCode = function(id) {
	const myreg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
	if (myreg.test(id)) {
		return false
	} else {
		return true
	}
}

// 打电话
Vue.prototype.contact = function(phone) {
	// 参考官网
	uni.makePhoneCall({
		phoneNumber: phone
	})
}

// 七牛云上传
Vue.prototype.uploadFile = function(filePath, utoken, url, bucket, key) {
	var promise = new Promise((resolve, reject) => {
		// console.log('七牛云上传',qnyUpload.upload(filePath));
		qnyUpload.upload(filePath,
			(res) => {
				resolve(res)
			},
			(error) => {
				reject(error)
			}, {
				region: 'SCN',
				uploadUrl: url,
				domain: '',
				bucket: bucket,
				uptoken: utoken,
				key: key
			}
		)
	})
	return promise;
	// 七牛云方法调用
	// that.uploadFile(filepath, obj.token, url, "", key)
	// 	.then(
	// 		(upres) => {
	// 			let obj = url + '/' + upres.key;
	// 			that.ghWay(obj);
	// 		}, (uperr) => {
	// 			console.log('2222222', uperr);
	// 		}
	// 	)
}

// 微信、支付宝支付
Vue.prototype.zhifu = function(type, data) {
	return new Promise((resolve, reject) => {
		let provider;
		if (type == 1) {
			provider = 'alipay'
		} else if (type == 2) {
			provider = 'wxpay'
		}
		// console.log(data)
		uni.requestPayment({
			provider: provider,
			orderInfo: data, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
			success: res => {
				resolve(res)
			},
			fail: err => {
				this.toast(err)
			}
		});
	})
}

// h5支付宝支付--需调试
Vue.prototype.zfbH5 = function(orderInfo) {
	return new Promise((resolve, reject) => {
		let provider;

		let form = orderInfo;
		const div = document.createElement('formdiv');
		div.innerHTML = form;
		document.body.appendChild(div);
		document.forms[0].submit();
		div.remove();
	})
}

// h5微信支付--需调试
Vue.prototype.wxH5 = function(obj) {
	return new Promise((resolve, reject) => {
		let provider;

		var ua = window.navigator.userAgent.toLowerCase();
		let wxIf = false;
		if (ua.match(/MicroMessenger/i) == 'micromessenger') { //微信浏览器
			wxIf = true;
		} else {
			wxIf = false;
		}

		if (wxIf) { //微信浏览器
			WeixinJSBridge.invoke(
				'getBrandWCPayRequest', {
					"appId": obj.appId, //公众号ID，由商户传入 
					"timeStamp": obj.timeStamp, //时间戳，自1970年以来的秒数 
					"nonceStr": obj.nonceStr, //随机串 
					"package": obj.package,
					"signType": obj.signType, //微信签名方式： 
					"paySign": obj.paySign, //微信签名 
				},
				function(ress) {
					if (ress.err_msg == "get_brand_wcpay_request:ok") {
						// 支付成功
					}
				});
		} else { //普通浏览器
			if (obj.url) {
				window.location.replace(obj.url) //obj.url支付地址
			} else {
				that.$utils.showMsg('暂无法支付')
			}

		}
	})
}

//上传图片
Vue.prototype.upImgUr = function(filePath) {
	uni.showLoading({
		title: '上传中'
	})
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: $url.urlUp + `api/common/upload`,
			filePath: filePath,
			name: 'file',
			// header: {
			// 	Authorization: storeUserInfo.token,
			// },
			success: (res) => {
				uni.hideLoading();
				let obj = JSON.parse(res.data);
				resolve(obj.data);
			},
			fail: (err) => {
				uni.hideLoading();
				uni.showToast({
					title: err,
					icon: 'none'
				})
			}
		})
	})
}


/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.修改所有style里的width属性为max-width:100%
 * 3.img标签添加style属性：max-width:100%;height:auto
 * 4.去掉<br/>标签
 */
Vue.prototype.formatRichText = function(html) {

	// 去掉img标签里的style、width、height属性
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	// 修改所有style里的width属性为max-width:100%
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
			'max-width:100%;');
		return match;
	});
	// 去掉<br/>标签
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	// img标签添加style属性：max-width:100%;height:auto
	newContent = newContent.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:block;margin:0px auto;"');
	return newContent;
}